<?php

namespace app\common;

final class ObjectUtil
{
    /**
     * 移除一个对象中的某些属性
     *
     * @template T
     * @param T $data
     * @param mixed ...$fields
     * 
     * @return T
     */
    public static function emit(object $data, ...$fields): object
    {
        foreach ($fields as $field) {
            unset($data->{$field});
        }
        return $data;
    }

    /**
     * 把$data的值赋值进target
     *
     * @template T
     * @param T $target
     * @param array|object|T $data
     * 
     * @return T
     */
    public static function assign(object $target, array|object ...$data): object
    {
        foreach ($data as $tData) {
            if (is_array($tData)) {
                foreach ($tData as $key => $value) {
                    $target->{$key} = $value;
                }
            } else {
                foreach (get_object_vars($tData) as $key => $value) {
                    $target->{$key} = $value;
                }
            }
        }
        return $target;
    }

    /**
     * 从数组创建一个自定义对象
     * 
     * @template T
     * @param class-string<T> $objClass 模型类
     * @param array $data 数组数据
     * 
     * @return T
     */
    public static function fromArray(string $classString, array $data)
    {
        $obj = new $classString();
        return self::assign($obj, $data);
    }
}